# -*- coding: utf-8 -*-
from flask import Blueprint,request,jsonify,redirect
from common.libs.Helper import osp_render
from common.libs.Helper import getCurrentDate
from common.models.Storage import Storage
from common.libs.UrlManager import UrlManager
from application import db,app
route_storagy = Blueprint( 'storagy_page',__name__ )
from sqlalchemy import  or_

@route_storagy.route( "/index" )
def index():
    resq_data = {}
    req = request.values
    query = Storage.query
    count = query.count()  # 总共多少条记录
    # 搜索功能实现or_表示定义了一个规则
    if "mix_kw" in req:
        rule = or_(Storage.sid == req['mix_kw'],
                   Storage.mobile == req['mix_kw'])
        query = query.filter(rule)
    # state的查询
    if 'state' in req and int(req['state']) > -1:  # status默认为-1
        query = query.filter(Storage.state == req['state'])

    list = query.order_by(Storage.sid.desc()).all()#全量查询，倒叙排列
    resq_data['list'] = list
    resq_data['count'] = count
    resq_data['search_con'] = req
    resq_data['status_mapping'] = app.config['STATES_MAPPING']
    return osp_render( "storagy/index.html",resq_data)


@route_storagy.route( "/set" ,methods=['GET','POST'])
def set():
    if request.method == 'GET':  # 直接渲染
        resq_data = {}
        req = request.args
        sid = int(req.get('id', 0))
        storagy_info = None
        if sid:
            storagy_info = Storage.query.filter_by(sid=sid).first()
        resq_data['info'] = storagy_info
        return osp_render( "storagy/set.html",resq_data)

    resq = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values

    # 1、参数获取
    sid = req['sid'] if 'sid' in req else '0'
    state = req['state'] if 'state' in req else ''
    mobile = req['mobile'] if 'mobile' in req else ''
    vericode = req['vericode'] if 'vericode' in req else ''

    # 2、有效性校验
    if vericode is None or len(vericode) != 6:
        resq['code'] = -1
        resq['msg'] = '请输入符合规范的6位数取货密码~'
        return jsonify(resq)

    storagy_info = Storage.query.filter_by(sid = sid).first()
    # 新增还是编辑的判断，判断存柜有没有，有则是编辑(原则就是根据SID）
    if storagy_info:
        model_storagy = storagy_info  # 还是原来的那个对象
    else:
        # 如果新增则需要初始化Storage()
        model_storagy = Storage()  # 是否新增的关键是这一行代码
    # 4、写入数据库
    model_storagy.state = state
    model_storagy.mobile = mobile
    model_storagy.vericode = vericode
    db.session.add(model_storagy)
    db.session.commit()

    return jsonify(resq)

@route_storagy.route( "/ops" , methods = ["GET", "POST"])
def ops():
    resq = {'code': 200, 'msg': '操作成功~~', 'data': {}}
    req = request.values

    id= req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:
        resq['code'] = -1
        resq['msg'] = '请选择要操作的账号~'
        return jsonify(resq)

    if act not in ['remove', 'recover']:
        resq['code'] = -1
        resq['msg'] = '操作有误，请重试~'
        return jsonify(resq)

    info = Storage.query.filter_by(sid=id).first()

    if not info:
        resq['code'] = -1
        resq['msg'] = '指定账号不存在~'
        return jsonify(resq)
    if act == 'remove':
        #更新数据库
        db.session.delete(info)
        db.session.commit()
        return jsonify(resq)